
/**
 * 旅客类别表
 */
import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, Icon, DatePicker, Input, Select } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import '@ant-design/compatible/assets/index.css';
import { useRequest } from '@umijs/hooks';
import { useActivate } from 'react-activation';

import styles from './index.less';
import { paxTypeTable, paxTypeExport, queryCityInfo, queryVipRoom, getCheckedPaxType} from '../service';

import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { formatFlightNo, controlTableHeight } from '@/utils/pagesGeneralMethods'; // 页面通用方法

const { Option } = Select;
let hiddenData = null

const PaxTypeTable = () => {

  const { data: selectData } = useRequest(queryCityInfo);
  const {run:queryVipRoomFun,  data: vipRoomsData } = useRequest(queryVipRoom);
  const {run: getCheckedPaxTypeFun,  data: selectedPaxType } = useRequest(getCheckedPaxType);

  useActivate(()=>{
    queryVipRoomFun()
    getCheckedPaxTypeFun()
  })
  
  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const [isCollapse, controlC] = useState(true); //搜索面板是否折叠

  const actionRef = useRef();
  const ref = useRef();

  const [searchParams, setSearchParams] = useState('')

  const [exportFlag, handleExportFlag] = useState('')

  /**
   * 导出
   */
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = paxTypeExport(searchParams).then(res=>{
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
        let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
      elink.download = '旅客类型报表'+time+'.xls'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
      message.success('导出成功');
    }).catch(err => {
    });
  }

  // 搜索
  const beforeSearchSubmit = useCallback(params =>{
    params['flightDateBegin'] = params.flightDateBegin ? params.flightDateBegin.format('YYYY-MM-DD') : '';
    params['flightDateEnd'] = params.flightDateEnd ? params.flightDateEnd.format('YYYY-MM-DD') : '';
    params['optDateBegin'] = params.optDateBegin ? params.optDateBegin.format('YYYY-MM-DD') : '';
    params['optDateEnd'] = params.optDateEnd ? params.optDateEnd.format('YYYY-MM-DD') : '';
    if (!isCollapse) {
      setSearchParams(params)
      return params
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('flightDateBegin') === -1) {
          params.flightDateBegin = ''
        }
        if (Object.keys(params).indexOf('flightDateEnd') === -1) {
          params.flightDateEnd = ''
        }

        setSearchParams({...hiddenData, ...params})
        return { ...hiddenData, ...params}
        
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          flightDateBegin: moment(),
          flightDateEnd: moment()
        })
        hiddenData = null
        setSearchParams(params)
        return params
      }
    }
  }, [isCollapse]);

  const columns = [
    {
      title: '旅客类型',
      dataIndex: 'vipType',
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            placeholder="请选择"
            mode='multiple'
          >
            {
              selectedPaxType && selectedPaxType.map(item => {
                return <Option key={item.paxTypeCode}>{item.paxTypeName}</Option>
              })
            }
          </Select>
        );
      },
    },
    {
      title: '次数',
      dataIndex: 'count',
      width: 90,
      hideInSearch: true
    },
    {
      title: '航班起始日期',
      dataIndex: 'flightDateBegin',
      width: 120,
      order: 7,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      dataIndex: 'flightDateEnd',
      order: 6,
      width: 120,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '操作起始日期',
      dataIndex: 'optDateBegin',
      width: 120,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '操作结束日期',
      dataIndex: 'optDateEnd',
      width: 120,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '贵宾室',
      dataIndex: 'vipRoom',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '贵宾室',
      dataIndex: 'vipRoomId',
      hideInTable: true,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            placeholder="请选择"
            mode='multiple'
          >
            {
              vipRoomsData && vipRoomsData.map(item => {
                return <Option key={item.id}>{item.roomName}</Option>
              })
            }
          </Select>
        );
      },
    },
    {
      title: '操作员工号',
      dataIndex: 'operator',
      width: 120,
    },
  ];
  return (
    <div>
      <ProTable
        className={styles.vipPaxCharts}
        formRef={ref}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        scroll={{ x: 1300, y: controlTableHeight(isCollapse, 360, 470) }}
        size='small'
        search={{
          onCollapse:val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     flightNumber: hiddenData.flightNumber,
            //     org: hiddenData.org,
            //     dst: hiddenData.dst,
            //     compensateType: hiddenData.compensateType
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          },
        }}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>类别统计表</span>
          </div>
        }
        actionRef={actionRef}
        rowKey="index"
        rowSelection={false}
        tableAlertRender={false}
        toolBarRender={() => [
          <AuthComponent authCode="vipRoom.paxTypeCharts.export">
            <Button icon="download" type="primary"  onClick={handleExport}>
              导出
            </Button>
        </AuthComponent>
        ]}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        columns={columns}
        beforeSearchSubmit={beforeSearchSubmit}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          if (!params.flightDateBegin && !params.flightDateEnd) {
            params.flightDateBegin = moment().format('YYYY-MM-DD');
            params.flightDateEnd = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              flightDateBegin: moment(),
              flightDateEnd: moment()
            })
          }

          params.vipRoomId =  params.vipRoomId && params.vipRoomId.join(',')
          params.vipType = params.vipType && params.vipType.join(',')

          setSearchParams(params)
          return paxTypeTable(params)
        }}
      />
    </div>
  );
};

export default Form.create()(PaxTypeTable);
